﻿using System.Collections.Generic;
using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using TyMES.Model.BaseInformation;
using WalkingTec.Mvvm.Core;
using Newtonsoft.Json;
using TyMES.Communication;
using TyMES.Model.Record;
namespace TyMES.Services
{
    public class CodeCreateService
    {
        private readonly WTMContext context;
        private static readonly object _lockObj = new object();

        public CodeCreateService(WTMContext context)
        {
            this.context = context;
        }
        public async Task<ResponseBase> CreateCode(string codeTypeName, int sqt)
        {
            lock (_lockObj)
            {
                var type = context.DC.Set<CodeType>().Where(x => x.CodeName == codeTypeName).ToList();
                if (type.Count < 1)
                    return new ResponseBase(false, "条码类型管理表中没有此类型条码");
                //获取前缀
                string pre = type[0].CodeRegex+yearCodeDict[DateTime.Today.Year];
                int month = DateTime.Today.Month;
                int day = DateTime.Today.Day;
                string mixdate = month.ToString("D2") + day.ToString("D2");
                var lastCode = getlastCode(codeTypeName, pre, mixdate);

                var judge = JudgeRepeat(codeTypeName, pre + mixdate + lastCode);
                if (!judge.Success)
                    return new ResponseBase(false, judge.Mesg);
                InsertCodeStore(pre + mixdate + lastCode, codeTypeName);
                return new ResponseBase(true, pre + mixdate + lastCode);
            }
            
        }

        private string getlastCode(string codeType, string pre, string date)
        {
            var lastCode = context.DC.Set<CodeStore>().Where(x => x.CodeTypeName == codeType).OrderByDescending(x => x.CreateTime).FirstOrDefault();
            if (lastCode == null)
                return "00000";
            else
            {
                if (lastCode.Codevalue.Substring(pre.Length, 4) != date)
                    return "00000";
                else
                    return (int.Parse(lastCode.Codevalue.Substring(lastCode.Codevalue.Length - 5, 5)) + 1).ToString("D5");
            }
        }

        public void InsertCodeStore(string code,string codeType)
        {
            try
            {
               
                 
                CodeStore thiscode = new CodeStore();
                thiscode.CodeTypeName = codeType;
                thiscode.Codevalue = code;
                thiscode.CreateTime = DateTime.Now;
                context.DC.Set<CodeStore>().Add(thiscode);
                context.DC.SaveChanges();
            }
            catch(Exception ex)
            {

            }
            
        }

       
    
        public ResponseBase JudgeRepeat(string CodeTypeName, string code)
        {
            try
            {
                var repeatCode = context.DC.Set<CodeStore>().Where(x => x.Codevalue == code&&x.CodeTypeName== CodeTypeName).FirstOrDefault();
                if (repeatCode != null)
                    return new ResponseBase(false, code + "此条码重复使用");
                return new ResponseBase(true, "");
            }
            catch(Exception ex)
            {
                return new ResponseBase(false, code + "校验异常"+ex.Message);
            }
        }
        Dictionary<int, string> yearCodeDict = new Dictionary<int, string>
        {
            {2024,"R" },
            {2025,"S" },
            {2026,"T" },
            {2027,"V" },
            {2028,"W" },
            {2029,"X" },
            {2030,"Y" },
            {2031,"1" },
            {2032,"2" }
        };

        Dictionary<int, string> monthCodeDict = new Dictionary<int, string>
        {
            {1,"1" },
            {2,"2" },
            {3,"3" },
            {4,"4" },
            {5,"5" },
            {6,"6" },
            {7,"7" },
            {8,"8" },
            {9,"9" },
            {10,"0" },
            {11,"A" },
            {12,"B" }
        };

        /// <summary>
        ///总成条码生成
        /// </summary>
        /// <param name="codeTypeName"></param>
        /// <param name="sqt"></param>
        /// <returns></returns>
        public async Task<ResponseBase> CreateShipCode(string codeTypeName, int sqt)
        {
            lock (_lockObj)
            {
                var type = context.DC.Set<CodeType>().Where(x => x.CodeName == codeTypeName).ToList();
                if (type.Count < 1)
                    return new ResponseBase(false, "条码类型管理表中没有此类型条码");
                //获取前缀

                int year = DateTime.Now.Year;
                string pre = type[0].CodeRegex;
                int month = DateTime.Today.Month;
                int day = DateTime.Today.Day;
                string yearmixdate = yearCodeDict[DateTime.Today.Year]+ monthCodeDict[DateTime.Today.Month] + day.ToString("D2");
                var lastCode ="B"+ getshipmentlastCode(codeTypeName, pre, yearmixdate);

                var judge = JudgeRepeat(codeTypeName, pre + yearmixdate + lastCode);
                if (!judge.Success)
                    return new ResponseBase(false, judge.Mesg);
                InsertCodeStore(pre + yearmixdate + lastCode, codeTypeName);
                return new ResponseBase(true, pre + yearmixdate + lastCode);
            }

        }

        private string getshipmentlastCode(string codeType, string pre, string date)
        {
            var lastCode = context.DC.Set<CodeStore>().Where(x => x.CodeTypeName == codeType).OrderByDescending(x => x.CreateTime).FirstOrDefault();
            if (lastCode == null)
                return "0001";
            else
            {
                if (lastCode.Codevalue.Substring(pre.Length, 4) != date)
                    return "0001";
                else
                    return (int.Parse(lastCode.Codevalue.Substring(lastCode.Codevalue.Length - 4, 4)) + 1).ToString("D4");
            }
        }

    }
}

